/**
 * 
 */
package org.vsg.stock.dzh;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;

/**
 * @author vison
 *
 */
public class ZipDataToFile {
	
	
	public void zipAndOutputFile(File orgFolder , File outputFile) {
		
		File[] subOrgFilders = orgFolder.listFiles();
		
		String fileName = null;
		
		ZipOutputStream zipOut = null;
		
		for (int i = 0 ; i < subOrgFilders.length ; i++) {
			if (subOrgFilders[i].isFile() ) {
				continue;
			}
			fileName = subOrgFilders[i].getName();
			String zipFileName = fileName+ ".zip";
			
			System.out.println("zip file " + zipFileName + " begin!");
			try {
				zipOut = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(new File(outputFile,zipFileName)) ) );
				zipOut.setLevel(9);
				this.zip( subOrgFilders[i] , zipOut);
			
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				try {
					zipOut.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			
			System.out.println("zip file " + zipFileName + " end!");
			
			
			try {
				FileUtils.deleteDirectory( subOrgFilders[i] );
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		
	}
	
	private void zip(File orgFolder , ZipOutputStream zipOut) throws IOException {
		File[] files = orgFolder.listFiles();
		File file = null;
		FileInputStream fis = null;
		for (int i = 0 ; i < files.length ; i++) {
			file = files[i];
			if ( file.isFile() ) {
				fis = new FileInputStream(file);
				
				zipOut.putNextEntry( new ZipEntry(file.getName()) );

				// --- enter file stream ---
				IOUtils.copy( fis, zipOut);
				
				zipOut.closeEntry();
				fis.close();

			}
		}
	}
	
	

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		File tickFile = new File("resources//data//tick");
		
		File outputFile = new File("E://stock_data//ticks");
		//File outputFile = new File("resources//data//tick");
		
		
		ZipDataToFile zdtf = new ZipDataToFile();
		
		zdtf.zipAndOutputFile(tickFile , outputFile);

	}

}
